﻿using System;
using System.Data;
using System.Drawing;
using System.IO;
using BONSAI.BLL;
using BONSAI.Common;
using BONSAI.Common.DTO;
using BONSAI.Common.Enum;

namespace BONSAI.Admin.UC
{
    public partial class PhotoUpdate : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                BindLoad();
        }
        public void BindLoad()
        {
            if (Request.QueryString["id"] != null)
            {
                var table = (new PhotosBO()).GetByID(Request.QueryString["id"]);
                if (table != null)
                {
                    if (table.thumbnail != null)
                    {
                        Image1.ImageUrl = table.thumbnail;
                        Session[BONSAIConstants.OLD_THUMBNAIL] = table.thumbnail;
                        Session[BONSAIConstants.OLD_PREVIEW] = table.preview;
                    }
                }
            }
                // Bind Alobum
            if (Request.QueryString["type"] != null)
            {
                var tableTours = (new ProductsBo()).GetById(Request.QueryString["type"]);
                if (tableTours != null)
                {
                    Label1.Text = tableTours.NameFull;
                }
            }
        }
        protected void btcapnhat_Click(object sender, EventArgs e)
        {
            // cập nhật
            if (Request.QueryString["id"] == null)// insert
            {
                var tableToursAs = (new PhotosBO()).GetByProductId(Request.QueryString["type"]);
                if (tableToursAs.Count > 5)
                {
                    WebMBox.Show("Danh sách hình ảnh đã đày. Không thể thêm mới.");
                    return;
                }
                var photosDto = new PhotosDTO
                                    {
                                        ProductsID = Request.QueryString["type"],
                                        Createdate = DateTime.Now
                                    };
                bool error = false;
                UploadImageForAdd(photosDto, error, BONSAIConstants.RELATIVE_PHOTOS.PRODUCTS);

                (new PhotosBO()).Insert(photosDto);
                WebMBox.Show("Danh sách hình ảnh. Thêm mới thành công.");
                return;
            }
            else// update
            {
                var photosDto = new PhotosDTO
                {
                    PhotosID = Request.QueryString["id"],
                    ProductsID = Request.QueryString["type"],
                    Createdate = DateTime.Now
                };
                bool error = false;
                UploadImageForUpdate(photosDto, error, BONSAIConstants.RELATIVE_PHOTOS.PRODUCTS);
                (new PhotosBO()).Insert(photosDto);
                WebMBox.Show("Danh sách hình ảnh. Cập nhựt thành công.");
                return;
            }

            //=================================
            
           
        }

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            Response.Redirect("PhotoManager.aspx?type=" + Request.QueryString["type"]);
        }

        #region UploadImageForAdd
        /// <summary>
        /// Method : UploadImageForAdd
        /// Author : LinhVM
        /// Creation date : 22.Jul.2009
        /// </summary>
        /// <param name="newsDTO"></param>
        /// <param name="error"></param>
        /// <param name="relativePhotos"></param>
        /// <returns></returns>
        private bool UploadImageForAdd(PhotosDTO info, bool error, string relativePhotos)
        {
            // First we check to see if the user has selected a file
            if (!FileUpload2.HasFile)
            {
                return error;
            }
            // Check if the directory we want the image uploaded to actually exists or not
            if (!Directory.Exists(MapPath(relativePhotos)))
            {
                // If it doesn't then we just create it before going any further
                Directory.CreateDirectory(MapPath(relativePhotos));
            }

            // get server path to save image
            string pathServer = Server.MapPath(relativePhotos);

            // upload image to server
            try
            {
                // resize before save image
                // Create a bitmap of the content of the fileUpload control in memory
                Bitmap originalBMP = null;
                originalBMP = new Bitmap(FileUpload2.FileContent);
                string relativeImageUrl = string.Empty;
                string relativePreviewUrl = string.Empty;
                // make thumbnail and preview for image
                int result = 0;
                result = BONSAIUtils.ImageUtil.DoImageTasks(originalBMP, pathServer, relativePhotos,
                                                                      ref relativeImageUrl, ref relativePreviewUrl,
                                                                      UploadImageEnum.PRODUCT_IMAGE, "");

                if (result == 1)
                {
                    info.thumbnail = relativeImageUrl;
                    info.preview = relativePreviewUrl;
                    error = false;
                }
                else
                {
                    error = true;
                }
            }
            catch (Exception)
            {
                error = true;
            }

            return error;
        }

        #endregion UploadImageForAdd

        #region UploadImageForUpdate
        /// <summary>
        /// Method : UploadImageForUpdate
        /// Author : LinhVM
        /// Creation date : 22.Jul.2009
        /// </summary>
        /// <param name="info"></param>
        /// <param name="error"></param>
        /// <param name="relativePhotos"></param>
        /// <returns></returns>
        private bool UploadImageForUpdate(PhotosDTO info, bool error, string relativePhotos)
        {
            // First we check to see if the user has selected a file

            if (!FileUpload2.HasFile)
            {
                if (Session[BONSAIConstants.OLD_THUMBNAIL] == null)
                {
                    
                    error = true;
                    return error;
                }

                info.thumbnail = Session[BONSAIConstants.OLD_THUMBNAIL].ToString();
                info.preview = Session[BONSAIConstants.OLD_PREVIEW].ToString();

                error = false;
                return error;
            }

            // Check if the directory we want the image uploaded to actually exists or not
            if (!Directory.Exists(MapPath(relativePhotos)))
            {
                // If it doesn't then we just create it before going any further
                Directory.CreateDirectory(MapPath(relativePhotos));
            }

            // get server path to save image
            string pathServer = Server.MapPath(relativePhotos);

            // upload image to server
            try
            {
                // resize before save image

                // Create a bitmap of the content of the fileUpload control in memory
                Bitmap originalBMP = null;

                originalBMP = new Bitmap(FileUpload2.FileContent);

                string relativeImageUrl = string.Empty;
                string relativePreviewUrl = string.Empty;

                // make thumbnail and preview for image
                int result = 0;

                result = BONSAIUtils.ImageUtil.DoImageTasks(originalBMP, pathServer, relativePhotos,
                                                                      ref relativeImageUrl, ref relativePreviewUrl,
                                                                      UploadImageEnum.PRODUCT_IMAGE, "");

                if (result == 1)
                {
                    // upload image successful
                    // set relative url
                    BONSAIUtils.ImageUtil.ClearOldImageOnServer(
                                   Server.MapPath(BONSAIConstants.RELATIVE_PHOTOS.PRODUCTS),
                                   Session[BONSAIConstants.OLD_THUMBNAIL].ToString());

                    BONSAIUtils.ImageUtil.ClearOldImageOnServer(
                        Server.MapPath(BONSAIConstants.RELATIVE_PHOTOS.PRODUCTS),
                        Session[BONSAIConstants.OLD_PREVIEW].ToString());



                    info.thumbnail = relativeImageUrl;
                    info.preview = relativePreviewUrl;
                    error = false;
                }
                else
                {
                    error = true;
                }

            }
            catch (Exception)
            {
                error = true;
            }

            return error;
        }

        #endregion UploadImageForUpdate
    }
}